<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { toNumber } from 'lodash-es'
import { GetData, PatchDetailsPassword, PatchListSort } from '@/api/modules/peopleManagement.ts'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const userRole = toNumber(userStore.role) // 获取当前登录用户权限

const router = useRouter()
const inquireFrom = reactive({
  account: '',
  mobile: '',
  role: '',
  enable: '',
})
const dataList: any = ref([])
// 加载
const loading = ref(false)
const total = ref(0) // 总数据数
let PageSize = 10 // 每页条数
let PageNum = toNumber(localStorage.getItem('currentPage')) || 1

// 获取数据
function GetDataList(PageIndex: number = 1, PageSize: number = 10) {
  loading.value = true
  const params = {
    PageIndex,
    PageSize,
    ...(inquireFrom.account && { Account: inquireFrom.account }),
    ...(inquireFrom.mobile && { Mobile: inquireFrom.mobile }),
    ...(inquireFrom.role && { Role: inquireFrom.role }),
    ...(inquireFrom.enable && { Enable: inquireFrom.enable }),
  }
  GetData(params).then((res: any) => {
    if (res.succeeded) {
      dataList.value = res.data.items
      total.value = res.data.total
      if (userRole === 1) {
        dataList.value = dataList.value.map((item: any) => ({
          ...item,
          isMatch: false,
        }))
      }
      else if (userRole === 2) {
        const account = userStore.account
        dataList.value = dataList.value.map((item: any) => {
          if (item.account === account) {
            return { ...item, isMatch: false }
          }
          else {
            return { ...item, isMatch: true }
          }
        })
      }
      else {
        dataList.value = dataList.value.map((item: any) => ({
          ...item,
          isMatch: true,
        }))
      }
      loading.value = false
    }
    else {
      ElMessage.error('查询失败')
      loading.value = false
    }
  })
}

// 查询
function Inquire() {
  GetDataList(1, PageSize)
}
// 添加
function AddEvent() {
  router.push({
    name: 'PeopleManagementDetail',
  })
}
// 获取身份
function getRoleName(role: number) {
  const roleObj = {
    1: '管理员',
    2: '管理员',
    3: '商务',
    4: '运营',
    5: '客服',
    6: '财务',
  } as { [index: number]: string }
  return roleObj[role] || '未定义'
}
// 改变状态
function ChangeDataType(row: any) {
  const params = {
    enable: row.enable,
    id: row.id,
  }
  if (row.isMatch) {
    ElMessage.error('您无权修改该用户状态')
    return
  }
  PatchListSort(params).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('操作成功')
    }
    else {
      ElMessage.error('修改失败')
      GetDataList(PageNum, PageSize)
    }
  })
}
// 编辑
function Redact(message: any) {
  localStorage.setItem('currentPage', `${PageNum}`)
  router.push({
    name: 'PeopleManagementDetail',
    query: {
      id: message.id,
    },
  })
}

const dialogFormVisible = ref(false)

interface RuleForm {
  id: string
  password?: string
  newPassword: string
  notarizePassword?: string
}
const changePassFromRef = ref<FormInstance>()

const changePassFrom = reactive<RuleForm>({
  id: '',
  password: '',
  newPassword: '',
  notarizePassword: '',
})
const rules = reactive({
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
  ],
  notarizePassword: [
    { required: true, message: '请再次输入密码确认', trigger: 'blur' },
  ],
})
function ChangePassword(message: any) {
  // 判断身份非超级管理员和管理员
  if (message.role !== 1 && message.role !== 2) {
    if (message.account !== userStore.account) {
      ElMessage.error('您无权修改该用户密码')
      return false
    }
  }
  // 添加id，清空页面弹窗中的表单数据
  changePassFrom.id = message.id
  changePassFrom.password = ''
  changePassFrom.newPassword = ''
  changePassFrom.notarizePassword = ''
  dialogFormVisible.value = true
}

async function SetNewPassword() {
  try {
    const isValid = await changePassFromRef.value?.validate()
    if (isValid) {
      if (changePassFrom.newPassword !== changePassFrom.notarizePassword) {
        ElMessage.error('两次输入的密码不一致')
        return
      }
      const params = {
        id: changePassFrom.id,
        password: changePassFrom.password,
        newPassword: changePassFrom.newPassword,
      }
      const res: any = await PatchDetailsPassword(params)
      if (res.succeeded) {
        ElMessage.success('修改成功')
        dialogFormVisible.value = false
      }
      else {
        ElMessage.error(`修改失败${res.errors}`)
      }
    }
  }
  catch (error) {
    // 处理验证过程中的错误
    console.error('处理验证过程中的错误:', error)
  }
}

// 页码
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return toNumber(localStorage.getItem('currentPage')) || 1
})

onMounted(() => {
  if (localStorage.getItem('currentPage') !== null) {
    GetDataList(toNumber(localStorage.getItem('currentPage')), 20)
    localStorage.removeItem('currentPage')
  }
  else {
    GetDataList()
  }
})
</script>

<template>
  <PageMain>
    <SearchBar :show-toggle="false">
      <div class="header">
        <el-form>
          <div class="from">
            <el-form-item label="账户名称">
              <el-input v-model="inquireFrom.account" placeholder="请输入账户名" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="inquireFrom.mobile" placeholder="请输入手机号" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="身份">
              <el-select v-model="inquireFrom.role" placeholder="请选择身份" clearable>
                <el-option key="1" label="超级管理员" :value="1" />
                <el-option key="2" label="管理员" :value="2" />
                <el-option key="3" label="商务" :value="3" />
                <el-option key="4" label="运营" :value="4" />
                <el-option key="5" label="客服" :value="5" />
                <el-option key="6" label="财务" :value="6" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="inquireFrom.enable" placeholder="请选择状态" clearable>
                <el-option key="1" label="正常" :value="true" />
                <el-option key="2" label="冻结" :value="false" />
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div class="text-right">
          <el-button @click="Inquire">
            查询
          </el-button>
        </div>
      </div>
    </SearchBar>
    <ElDivider border-style="dashed" />
    <div class="mb-5 text-right">
      <el-button type="success" @click="AddEvent">
        添加用户
      </el-button>
    </div>
    <el-table v-loading="loading" :data="dataList" stripe style="width: 100%;" border>
      <el-table-column align="center" prop="account" label="账户名称" width="350" />
      <el-table-column align="center" prop="mobile" label="手机号" width="240" />
      <el-table-column align="center" prop="description" label="备注" width="280">
        <template #default="scope">
          {{ scope.row.description ? scope.row.description : '无' }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="role" label="身份" width="240">
        <template #default="scope">
          <el-tag type="primary">
            {{ getRoleName(scope.row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="enable" label="启用" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.enable"
            :disabled="scope.row.isMatch"
            @click="ChangeDataType(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" min-width="220">
        <template #default="scope">
          <div class="table-button">
            <el-button type="primary" :disabled="scope.row.isMatch" @click="Redact(scope.row)">
              编辑
            </el-button>
            <el-button type="primary" @click="ChangePassword(scope.row)">
              修改密码
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="height: 10px;" />
    <el-pagination
      :page-sizes="[5, 10, 20, 50, 100]"
      layout="total, sizes, ->, prev, pager, next, jumper"
      :total="total"
      :default-current-page="nowPageNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
      <el-form ref="changePassFromRef" style="max-width: 600px;" :model="changePassFrom" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon>
        <el-form-item v-if="userStore.role !== '1' && userStore.role !== '2'" label="当前密码" prop="password">
          <el-input v-model="changePassFrom.password" style="width: 240px;" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="changePassFrom.newPassword" style="width: 240px;" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="notarizePassword">
          <el-input v-model="changePassFrom.notarizePassword" style="width: 240px;" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="SetNewPassword">
            修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </PageMain>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;
  grid-gap: 20px;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
